package kevin.workplan.exception;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.json.MappingJacksonJsonView;


public class MyExceptionHandle implements HandlerExceptionResolver {
	private final static Logger log = LoggerFactory.getLogger(MyExceptionHandle.class);

    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
            Exception ex) {
        
       
        String message = "";
        if(ex instanceof BusinessException) {
            message = ex.getMessage();
        } else if(ex instanceof ServiceException) {
            message = "服务器异常";
        } else {
        	log.error("unknown error", ex);
            message = "未知错误";
        }
        
        ModelAndView model = null;
        String uri = request.getServletPath();
        if(uri!=null && uri.endsWith(".json")) {
	        Map<String, Object> result = new HashMap<String, Object>();
	        result.put("code", -1);
	        result.put("message", message);
	        model = new ModelAndView();
	        MappingJacksonJsonView v = new MappingJacksonJsonView();
	        v.setAttributesMap(result);
	        model.setView(v);
        } else {
        	request.setAttribute("errormsg", message);
        	model = new ModelAndView("error");
        }
        
        return model;
    }

}
